import 'package:get/get.dart';
import 'package:sinosheets/components/GBWebView/gb_webview_cache.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/utils/bus_utils.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';
import 'package:sinosheets/utils/language/isar_lang_service.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';

class SettingsLogic extends GetxController {
  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    getCacheSize();
    checkSheetShowCode();

    bus.on('code_update', (code) {
      update();
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  /// 清除缓存
  String cacheText = "";
  void getCacheSize() async {
    // 获取缓存信息
    final cache = GBWebViewCache();
    final cacheInfo = await cache.getCacheInfo();
    LogUtil.e('缓存大小: ${cache.getReadableCacheSize(cacheInfo['size'])}');
    LogUtil.e('缓存文件数: ${cacheInfo['count']}');
    LogUtil.e('缓存文件列表: ${cacheInfo['files']}');
    cacheText = cache.getReadableCacheSize(cacheInfo['size']);
    update();
    // 检查特定URL是否已缓存
    final isCached = await cache.isCached(
      HttpConfig.baseUrl,
    );
    LogUtil.e('URL是否已缓存: $isCached');
  }

  void onClearCacheClick() async {
    await IsarLangService().clearAll();
    await GBWebViewCache().clearCache();
    getCacheSize();
  }

  bool isShowCode = false;
  void checkSheetShowCode() {
    isShowCode = LSUtil.getSheetShowCode() == 'true';
    bool isValidateCode = LSUtil.getInviteCode()['isValid'] ?? false;

    if (isValidateCode) {
      isShowCode = true;
    }
    update();
  }
}
